﻿using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace mlnx_os_sysdump_analyzer
{
    public partial class Settings : Form
    {
        public DialogResult dialogResult = DialogResult.Cancel;

        /// <summary>
        /// constructor + initializing the panel.
        /// </summary>
        public Settings()
        {
            InitializeComponent();
            init();
        }
        //
        //----------------------------------------------------
        /// <summary>
        /// init the settings panel. get the latest saved settings and display them.
        /// </summary>
        private void init()
        {
            // add items from the settings file
            try
            {
            	initMarkersTable();
                initMessagesKeywordTable();
                initDmesgKeywordTable();
                printGapTextBox.Text = Properties.Settings.Default.logsIdleThresholdSec.ToString();
            }
            catch
            { }
        }
        //
        //----------------------------------------------------
        //

        /// <summary>
        /// display the text horizontally for a tabpage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingsTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Graphics g;
                string text;
                int x, y;
                SizeF textSize;
                TabControl ctlTab = (TabControl)sender;
                g = e.Graphics;
                text = ctlTab.TabPages[e.Index].Text;
                textSize = g.MeasureString(text, ctlTab.Font);
                x = e.Bounds.Left + 6;
                y = (int)(e.Bounds.Top + (e.Bounds.Height - textSize.Height) / 2);
                g.DrawString(text, ctlTab.Font, Brushes.Black, x, y);
            }
            catch { }
        }
        //
        //----------------------------------------------------
       
//        /// <summary>
//        /// import settings from a file
//        /// </summary>
//        /// <param name="sender"></param>
//        /// <param name="e"></param>
//        private void importButton_Click(object sender, EventArgs e)
//        {
//            try
//            {
//                OpenFileDialog ofd = new OpenFileDialog();
//                ofd.Filter = "mlnxconfig|*.mlnxconfig";
//                if (ofd.ShowDialog() == DialogResult.OK)
//                {
//                    if (ofd.FileName != "")
//                    {
//                        SettingsIO.Import(ofd.FileName);
//                        init();
//                        MessageBox.Show("The settings were loaded.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }   
//        }
        //
        //----------------------------------------------------
        
//        /// <summary>
//        /// export settings to a file
//        /// </summary>
//        /// <param name="sender"></param>
//        /// <param name="e"></param>
//        private void exportButton_Click(object sender, EventArgs e)
//        {
//            try
//            {
//                SaveFileDialog sfd = new SaveFileDialog();
//                sfd.Filter = "mlnxconfig|*.mlnxconfig";
//                if (sfd.ShowDialog() == DialogResult.OK)
//                {
//                    if (sfd.FileName != "")
//                    {
//                        SettingsIO.Export(sfd.FileName);
//                        MessageBox.Show("The settings were saved.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }
//        }
//        //
//        //----------------------------------------------------
        
//        /// <summary>
//        /// reset all settings to default
//        /// </summary>
//        /// <param name="sender"></param>
//        /// <param name="e"></param>
//        private void resetAllToDefaultButton_Click(object sender, EventArgs e)
//        {
//            try
//            {
//                if (MessageBox.Show("Default settings will be loaded.\nAre you sure you want to continue?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
//                {
//                    
//                    Properties.Settings.Default.Reset();
//                    init();
//                    MessageBox.Show("Default settings were restored.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
//                }
//            }
//            catch (Exception ex)
//            {
//                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }
//        }
//        //
//        //----------------------------------------------------
        
        /// <summary>
        /// reset to default the threshold for the gap size check in the messages file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printGapResetToDefaulButton_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.logsIdleThresholdSec = 10;
            printGapTextBox.Text = "10";
            // save changes
            Properties.Settings.Default.Save();
        }
        //
        //----------------------------------------------------
        

        /// set the threshold for the gap size check in the messages file.
        private bool savePrintGap()
        {
            try
            {
                if (!printGapTextBox.Text.Equals(""))
                {
                    int threshold = Int32.Parse(printGapTextBox.Text);
                    Properties.Settings.Default.logsIdleThresholdSec = threshold;
                    // save changes
                    Properties.Settings.Default.Save();
                }
                return true;
            }
            catch
            {
                MessageBox.Show("Illegal input in: 'Messages Print Gaps'\nThe time must be an interger number", "Illegal input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                printGapResetToDefaulButton_Click(null, null);
                return false;
            }
        }
        //
        //----------------------------------------------------
        
        
        void okBtnClick(object sender, EventArgs e)
        {
        	// save all settings
        	if (!savePrintGap())
        	{
        		return;
        	}
        	saveMarkers();
        	saveMessagesKeywords();
        	saveDmesgKeywords();
        	//
            dialogResult = System.Windows.Forms.DialogResult.OK;

        	// close window
			this.Close();
        }
        //
        //----------------------------------------------------
        
        // 
        void cancelBtnClick(object sender, EventArgs e)
        {
            dialogResult = System.Windows.Forms.DialogResult.Cancel;
        	this.Close();
        }
        //
        //----------------------------------------------------
        
        void markerSetColorBtnClick(object sender, EventArgs e)
        {
        	ColorDialog dg = new ColorDialog();
			dg.Color = Color.White;
			dg.ShowDialog();
			int rowIndx = markersDataGridView.CurrentCell.RowIndex;
			markersDataGridView.Rows[rowIndx].DefaultCellStyle.BackColor = dg.Color;
        }
        //
        //----------------------------------------------------
        
        void markerClearAllBtnClick(object sender, EventArgs e)
        {
        	markersDataGridView.Rows.Clear();
        }
        //
        //----------------------------------------------------
        
        private void initMarkersTable()
        {
        	// clear the markers dgv
            markersDataGridView.Rows.Clear();
            // get markers IEnumerator
        	MarkerListSett markerSettings = new MarkerListSett();
        	markerSettings.Reload();
     	   	IEnumerator ienum = markerSettings.Marker_List.MarkersEnumerator;
     	   	int rowInxd = 0;
           	while(ienum.MoveNext())
	        {
        		Marker marker1 = (Marker)ienum.Current;
        		markersDataGridView.Rows.Add(marker1.keywork);
        		markersDataGridView.Rows[rowInxd++].DefaultCellStyle.BackColor = marker1.markerColor;
	        }
        }
        //
        //----------------------------------------------------
        
        void MarkerResetBtnClick(object sender, EventArgs e)
        {
        	try
        	{
	        	MarkerList tmp = MarkerList.GetDefaultMarkersList();
	        	if (tmp != null)
	        	{
		        	// clear the markers dgv
		            markersDataGridView.Rows.Clear();
		            // 
		        	IEnumerator ienum = tmp.MarkersEnumerator;
		     	   	int rowInxd = 0;
		           	while(ienum.MoveNext())
			        {
		        		Marker marker1 = (Marker)ienum.Current;
		        		markersDataGridView.Rows.Add(marker1.keywork);
		        		markersDataGridView.Rows[rowInxd++].DefaultCellStyle.BackColor = marker1.markerColor;
			        }
	        	}
        	}
        	catch{}
        }
        //
        //----------------------------------------------------
        
        void MarkerDeleteBtnClick(object sender, EventArgs e)
        {
        	try
        	{
				int rowIndx = markersDataGridView.CurrentCell.RowIndex;
				if (rowIndx >= 0)
				{
					markersDataGridView.Rows.RemoveAt(rowIndx);
				}
        	}
        	catch{}
        }
        //
        //----------------------------------------------------
        
        // saveMarkers      
        private void saveMarkers()
        {
        	try
        	{
	        	MarkerList.ClearMarkers();
				// commit changes
				MarkerListSett markerSettings = new MarkerListSett();
	        	markerSettings.Reload();
				for (int row = 0 ; row < markersDataGridView.Rows.Count ; row++)
				{
					string keyword = (string)markersDataGridView[0, row].Value;
					Color color = markersDataGridView.Rows[row].DefaultCellStyle.BackColor;
					if (keyword != null && !keyword.Equals(""))
					{
						markerSettings.Marker_List.addMarker(keyword, color);
					}
				}
				markerSettings.Save();
				
        	}
        	catch {}
        }
        //
        //----------------------------------------------------              

        void MessagesClearBtnClick(object sender, EventArgs e)
        {
        	messagesKwDataGridView.Rows.Clear();
        }
        //
        //----------------------------------------------------
        
        void MessagesResetBtnClick(object sender, EventArgs e)
        {
			try
        	{
	        	// clear
				messagesKwDataGridView.Rows.Clear();
                // add default values
                string[] messagesKeywords = new string[] { ".ERR", "PLB", "crash", "go bit not cleared", "timed out", "Linux", "updt_role", "HERE" };
                for (int i = 0; i < messagesKeywords.Length; i++)
                {
                    messagesKwDataGridView.Rows.Add(messagesKeywords[i]);
                }
        	}
			catch {}
        }
        //
        //----------------------------------------------------
        
        private void saveMessagesKeywords()
        {
        	try
        	{
        		// clear default
                Properties.Settings.Default.messagesKeywords.Clear();
                for (int i = 0 ; i < messagesKwDataGridView.Rows.Count ; i++)
                {
                	string tmp = (string)messagesKwDataGridView[0, i].Value;
                	if (tmp != null && !tmp.Equals(""))
                	{
                		Properties.Settings.Default.messagesKeywords.Add(tmp);
                	}
                }
                // save changes
                Properties.Settings.Default.Save();	
        	}
        	catch{}
        }
        //
        //----------------------------------------------------
        
        private void initMessagesKeywordTable()
        {
        	try
        	{
	        	// clear
				messagesKwDataGridView.Rows.Clear();
				// 
	            Properties.Settings.Default.Reload();
	            for (int i = 0; i < Properties.Settings.Default.messagesKeywords.Count; i++)
	            {
	                messagesKwDataGridView.Rows.Add(Properties.Settings.Default.messagesKeywords[i]);
	            }
        	}
        	catch {}
        }
        //
        //----------------------------------------------------
        
        void MessagesDeleteBtnClick(object sender, EventArgs e)
        {
        	try
        	{
        		int rowIndx = messagesKwDataGridView.CurrentCell.RowIndex;
        		if (rowIndx >= 0)
        		{
        			messagesKwDataGridView.Rows.RemoveAt(rowIndx);
        		}
        	}
        	catch{}
        }
        //
        //----------------------------------------------------
        
        void DmesgClearAllBtnClick(object sender, EventArgs e)
        {
        	dmesgDataGridView.Rows.Clear();
        }
        //
        //----------------------------------------------------

        void DmesgResetBtnClick(object sender, EventArgs e)
        {
        	try
        	{
        		// clear
        		dmesgDataGridView.Rows.Clear();
                // add default values
                string[] dmesgKeywords = new string[] { "PLB", "not found", "error", "Call Trace"};
                for (int i = 0; i < dmesgKeywords.Length; i++)
                {
                    dmesgDataGridView.Rows.Add(dmesgKeywords[i]);
                }
        	}
        	catch {}
        }
        //
        //----------------------------------------------------

        private void initDmesgKeywordTable()
        {
        	try
        	{
	        	// clear
				dmesgDataGridView.Rows.Clear();
				// 
	            Properties.Settings.Default.Reload();
	            for (int i = 0; i < Properties.Settings.Default.dmesgKeywords.Count; i++)
	            {
	                dmesgDataGridView.Rows.Add(Properties.Settings.Default.dmesgKeywords[i]);
	            }
        	}
        	catch {}
        }
        //
        //----------------------------------------------------

        private void saveDmesgKeywords()
        {
        	try
        	{
        		// clear default
                Properties.Settings.Default.dmesgKeywords.Clear();
                for (int i = 0 ; i < dmesgDataGridView.Rows.Count ; i++)
                {
                	string tmp = (string)dmesgDataGridView[0, i].Value;
                	if (tmp != null && !tmp.Equals(""))
                	{
                		Properties.Settings.Default.dmesgKeywords.Add(tmp);
                	}
                }
                // save changes
                Properties.Settings.Default.Save();	
        	}
        	catch {}
        }
        //
        //----------------------------------------------------

        private void checkForDuplicate(DataGridView dgv, int newValRow, int newValCol)
        {
        	try
        	{
        		if (newValRow >= 0 && newValCol >= 0)
        		{
		        	string newVal = (string)dgv[newValCol, newValRow].Value;
		        	if (newVal != null)
		        	{
		        		for (int i = 0 ; i <dgv.Rows.Count ; i++)
		        		{
		        			if (i != newValRow)
		        			{
                                if (dgv[0, i].Value != null && dgv[0, i].Value.Equals(newVal))
		        				{
		        					MessageBox.Show("This keyword was already defined.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
		        					dgv[newValCol, newValRow].Value = "";
		        				} // end if (dgv[0, i].Value.Equals(newVal))
		        			} //end if (i != newValRow) 
		        		}// end (int i = 0 ; i <dgv.Rows.Count ; i++)
		        	}// end (newVal != null)
        		}// end if (newValRow >= 0 && newValCol >= 0)
        	}// end for
        	catch{}
        }
        //
        //----------------------------------------------------
      
        void MarkersDataGridViewCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        	checkForDuplicate(markersDataGridView, e.RowIndex, e.ColumnIndex);
        }
        //
        //----------------------------------------------------
       
        void MessagesKwDataGridViewCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        	checkForDuplicate(messagesKwDataGridView, e.RowIndex, e.ColumnIndex);
        }
        //
        //----------------------------------------------------
        
        void DmesgDataGridViewCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        	checkForDuplicate(dmesgDataGridView, e.RowIndex, e.ColumnIndex);
        }
        //
        //----------------------------------------------------
        
    }
}
